package com.example.http;

import lombok.extern.slf4j.Slf4j;
import org.apache.http.HttpEntity;
import org.apache.http.HttpHost;
import org.apache.http.HttpResponse;
import org.apache.http.auth.AuthScope;
import org.apache.http.auth.UsernamePasswordCredentials;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.conn.params.ConnRouteParams;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;

import java.io.IOException;
import java.io.UnsupportedEncodingException;


/**
 * @author ：wuhong-016
 * @version v1.0.0
 * @Create : 2021/1/27 13:39
 * @Description : TODO
 **/
public class HttpUtil {


    /**
     * HttpClient发送json
     *
     * @param url
     * @param content
     * @param charSet
     * @return
     */
    public static String sendByPost(String url, String content, String charSet) {
        System.out.println("接口请求路径：" + url);
        HttpPost post = new HttpPost(url);
        HttpEntity se;
        String retSrc = "";
        try {
            se = new StringEntity(content);
            // se = new StringEntity(content, charSet);
            post.setEntity(se);
            // 启用代理
            // HttpResponse httpResponse = getHttpClient().execute(post);
            // 不启用代理
            HttpResponse httpResponse = new DefaultHttpClient().execute(post);
            retSrc = EntityUtils.toString(httpResponse.getEntity());
        } catch (UnsupportedEncodingException e) {
            System.err.println("接口请求异常1：" + e);
        } catch (ClientProtocolException e) {
            System.err.println("接口请求异常2：" + e);
        } catch (IOException e) {
            System.err.println("接口请求异常3：" + e);
        }
        System.out.println("接口返回结果：" + retSrc);
        return retSrc;
    }


    /**
     * HttpClient 配置代理服务器
     *
     * @return
     */
    public static DefaultHttpClient getHttpClient() {
        DefaultHttpClient httpClient = new DefaultHttpClient();
        String proxyHost = "10.191.113.100";
        int proxyPort = 8002;
        String userName = "wuhong-016";
        String password = "Cpic@12345";
        httpClient.getCredentialsProvider().setCredentials(new AuthScope(proxyHost, proxyPort),
                new UsernamePasswordCredentials(userName, password));
        HttpHost proxy = new HttpHost(proxyHost, proxyPort);
        httpClient.getParams().setParameter(ConnRouteParams.DEFAULT_PROXY, proxy);
        return httpClient;
    }

}

